<?php
/**
 * Created by PhpStorm.
 * User: youlognit
 * Date: 2021-09-09
 * Time: 20:38
 */
namespace App\Admin\Forms;

use App\Models\ChannelConfig;
use Dcat\Admin\Form\Row;
use Dcat\Admin\Widgets\Form;
use Dcat\Admin\Traits\LazyWidget;
use Dcat\Admin\Contracts\LazyRenderable;

class FlowTimes extends Form implements LazyRenderable
{
    use LazyWidget; // 使用异步加载功能

    // 处理请求
    public function handle(array $input)
    {
        $names = [
            'pv' => 'PV',
            'uv' => 'UV',
            'ip' => 'IP',
        ];
        try {
            $data = [];
            foreach($input as $key => $item){
                $data[substr($key, 0, 2)][] = $item;
            }
            foreach($data as $datKey => $dataItem){
                $query = ChannelConfig::query();
                $obj = $query->where('key', $datKey)->first();
                if($obj){
                    $obj->value = implode(',', $dataItem);
                    $obj->save();
                }else{
                    $query->insert([
                        'name'          => $names[$datKey],
                        'key'           => $datKey,
                        'value'         => implode(',', $dataItem),
                        'created_at'    => date('Y-m-d H:i:s'),
                    ]);
                }
            }

            return $this->response()->success('添加成功')->redirect('/channel-report');
        }catch(\Exception $e){
            // 打印错误
            return $this->response()->success('添加失败');
        }
    }

    public function form()
    {
        $this->row(function ($row) {
            $row->width(4)->text('pv1', 'PV')->default(0);
            $row->width(4)->text('pv2', '&nbsp;')->default(0);
            $row->width(4)->text('pv3', '&nbsp;')->default(0);
        });
        $this->row(function ($row) {
            $row->width(4)->text('uv1', 'UV')->default(0);
            $row->width(4)->text('uv2', '&nbsp;')->default(0);
            $row->width(4)->text('uv3', '&nbsp;')->default(0);
        });
        $this->row(function ($row) {
            $row->width(4)->text('ip1', 'IP')->default(0);
            $row->width(4)->text('ip2', '&nbsp;')->default(0);
            $row->width(4)->text('ip3', '&nbsp;')->default(0);
        });

    }

    // 返回表单数据，如不需要可以删除此方法
    public function default()
    {
        return [
            'pv'    => '',
            'uv'    => '',
            'ip'    => '',
        ];
    }
}
